package com.biz.primus.service.push.service;


import com.biz.primus.base.enums.push.NotifyType;
import com.biz.primus.base.vo.push.Notification;
import com.biz.primus.service.push.service.interfaces.IPusher;
import com.biz.primus.service.push.util.PushUtil;
import com.xiaomi.push.sdk.ErrorCode;
import com.xiaomi.xmpush.server.Message;
import com.xiaomi.xmpush.server.Result;
import com.xiaomi.xmpush.server.Sender;
import com.xiaomi.xmpush.server.TargetedMessage;
import java.io.IOException;
import java.util.List;
import javax.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.json.simple.parser.ParseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by david-liu on 2016/03/28 14:32.
 */
@Component
@Slf4j
public class MIPusher implements IPusher {

    @Autowired
    private Sender miSender;

    @PostConstruct
    public void setup() {
        log.info("Create bean {} success.", getClass());
    }

    @Override
    public void push(Notification notification) {
        Result result;
        try {
            if (notification.getNotifyType() == NotifyType.P2P) {
                Message message = PushUtil.buildMiPushMessage(notification);
                List<String> targets = PushUtil.buildMiPushTarget(notification);
                result = miSender.sendToAlias(message, targets, Notification.MI_RETRY_TIMES);
            } else {
                List<TargetedMessage> targetedMessages = PushUtil.buildMiTargetPushMessages(notification);
                result = miSender.send(targetedMessages, Notification.MI_RETRY_TIMES);
            }
            if (result.getErrorCode() == ErrorCode.Success) {
                log.info("使用小米推送服务发送消息成功");
            } else {
                log.warn("使用小米推送服务发送消息失败.错误码[{}] 失败原因[{}]", result.getErrorCode(), result.getReason());
            }
        } catch (IOException | ParseException e) {
            log.warn("使用小米推送消息失败");
        }
    }
}
